package com.kerbores.blog.aop;

import javax.servlet.http.HttpServletRequest;

import org.nutz.aop.InterceptorChain;
import org.nutz.aop.MethodInterceptor;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;

import com.kerbores.blog.bean.Analytics;
import com.kerbores.blog.bean.User;
import com.kerbores.blog.constant.Constant;
import com.kerbores.blog.dao.IAnalyticsDao;
import com.kerbores.utils.ua.UserAgent;

/**
 * @author Ixion <br>
 *         create at 2014年10月26日
 */
@IocBean(name = "addup")
public class AccessAddUp implements MethodInterceptor {

	@Inject
	private IAnalyticsDao analyticsDao;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.nutz.aop.MethodInterceptor#filter(org.nutz.aop.InterceptorChain)
	 */
	@Override
	public void filter(InterceptorChain chain) throws Throwable {

		String uri = Mvcs.getReq().getRequestURI();
		String referer = Mvcs.getReq().getHeader("referer");
		Object obj = Mvcs.getReq().getSession().getAttribute(Constant.LOGIN_USER_SESSION_KEY);
		int visterId = obj == null ? -99 : ((User) obj).getId();
		Analytics analytics = new Analytics();
		analytics.setVisitorId(visterId);
		analytics.setIp(getIp(Mvcs.getReq()));
		analytics.setOrigin(referer);
		analytics.setResource(uri);
		UserAgent uaAgent = new UserAgent(Mvcs.getReq().getHeader("user-agent"));
		analytics.setOs(uaAgent.getOperatingSystem().getName());
		analytics.setOsVersion(uaAgent.getOperatingSystem() + "");
		analytics.setBrowser(uaAgent.getBrowser().getName());
		analytics.setBrowserVersion(uaAgent.getBrowserVersion().getVersion());
		analyticsDao.creatTable();
		if (analytics.getBrowser().indexOf("BOT") < 0) {// 忽略爬虫
			analyticsDao.save(analytics);
		}
		chain.doChain();
	}

	private String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
